﻿/*----------------------------------------------------------------------------------------
*
*  Copyright 2019, Gao Hai Hui, <fromzeropoint@126.com>.  All rights reserved.
*  https://gitee.com/helloworldghh/xoskit.git
*  Use of this source code is governed by a MIT license
*  that can be found in the License file.
*
----------------------------------------------------------------------------------------*/
#ifndef __7BC2D1ED_03EB_483f_B89C_1C0063E0C7AE__
#define __7BC2D1ED_03EB_483f_B89C_1C0063E0C7AE__

#include "../tools/head.h"

/////////////////////////////////////////////////////////////////////////////////////////
// 

namespace xos
{
    // 
    // select_impl
    // 
    class select_impl : public xos_stl::mem_item< release_impl< select_impl >, thread_lock >,
        public i_select
    {
    public:
        typedef release_impl< select_impl > T;

    public:
        enum
        {
            MAX_SELECT_NUM = 1000
        };
        
    public:
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //

        static int get_addr( POOL *** pppPool, LIST *** pppList );

    public:
        select_impl();
        ~select_impl();

    public:
        int init();
        int term();

    protected:
        // 
        // internal parameters
        // 
        i_socket * m_pWrites[MAX_SELECT_NUM];
        int m_sWrites[MAX_SELECT_NUM];
        int m_nWritesNum;

        i_socket * m_pErrors[MAX_SELECT_NUM];
        int m_sErrors[MAX_SELECT_NUM];
        int m_nErrorsNum;

        i_socket * m_pReads[MAX_SELECT_NUM];
        int m_sReads[MAX_SELECT_NUM];
        int m_nReadsNum;

        // 
        // 最大的socket句柄加1
        // 
        int m_nMaxSocket;

    protected:
        int prepare_select_handles( i_socket * pInputHandles[], int nInputNum, 
            i_socket ** pOutputHandles, int * pOutInts, int & nOutNum );

        int helper_select( i_socket * pRead[], int & nReadNum, 
            i_socket * pWrite[], int & nWriteNum, 
            i_socket * pError[], int & nErrorNum, 
            xos::xos_u32 uTimeout );

    public:
        // 
        // select function. the same as os select.
        // 
        // -1    : error
        // 0     : timeout
        // other : select num
        // 
        int select( i_socket * pRead[], int & nReadNum, 
            i_socket * pWrite[], int & nWriteNum, 
            i_socket * pError[], int & nErrorNum, 
            xos::xos_u32 uTimeout );
    };
} // xos

#endif // __7BC2D1ED_03EB_483f_B89C_1C0063E0C7AE__
